<?php
namespace src\logic;
use \classlib\core as C;
class lmailer {
	const MExpire = 86400;
	const EMAILEXPIRE = 300;
	/**
	 * 获取邮件发送模板内容信息,直接进行内容替换
	 * @param unknown $data
	 * @param unknown $tpl
	 * @return array title|tpl
	 */
	public static function tpl_compiler($data, $tpl) {
		static $tpls = array();
		if (!isset($tpls[$tpl])) {//二次批量发送的时候缓存住信息
			$lang  = C\lang::inst('web')->get('mailer', $tpl);
			if (!$lang) {
				return false;
			}
			list($title, $html) = explode('<@>', $lang, 2);
			$html  = COREDIR.'/src/_app/view/'.trim($html);
			if (!file_exists($html)) {
				return false;
			}
			$html = file_get_contents($html);
			$tpls[$tpl] = array('title'=>trim($title), 'tpl'=>$html);
		}
		$html = $tpls[$tpl]['tpl'];
		foreach ($data as $key=>$val) {
			$html = str_replace('{{'.$key.'}}', $val, $html);
		}
		$data = array('title'=>$tpls[$tpl]['title'], 'tpl'=>$html);
		return $data;
	}
	
	//获取邮箱验证码资料信息
	public static function setvcode($email, $otype, $userid=0, $vtype=2) {
		$vcode = C\rand_str(16);
		$field = array('vcode'=>$vcode, 'userid'=>$userid, 'vdata'=>$email, 'vtype'=>$vtype, 'otype'=>$otype,
				'expire'=>C\config::$nowtime + self::MExpire, 'status'=>0, 'stime'=>C\config::$nowtime);
		C\model::load('main.log.vcode')->new_one($field);
		return $vcode;
	}
	
	//验证会员的邮箱注册码资料信息
	public static function checkvcode($email, $vcode, $otype, $vtype=2) {
		$vorm  = C\model::load('main.log.vcode');
		$where = array('vtype'=>$vtype, 'otype'=>$otype, 'vcode'=>$vcode, 'vdata'=>$email);
		$data  = $vorm->get_item($where, '*', 'id', \classlib\orm::DESC);
		if (empty($data)) {
			return -1;
		} else if ($data['expire'] < C\config::$nowtime) {
			return -2;
		} else if ($data['status'] != 0) {
			return -3;
		}
		C\model::load('main.log.vcode')->save($data['id'], array('status'=>1));
		return $data['userid'];
	}
	
	//绑定邮箱发送邮件验证
	public static function setingssend($view, $user, $email) {
		$vcode= self::setvcode($email, 3, $user['userid']);
		$skey = sprintf('%s;%s', $vcode, $email);
		$skey = \classlib\crypt\xxtea::encrypt($skey);
		$link = C\router::base_url().C\router::get_url('profile/setting', 'emailcheck').'?s='.urlencode($skey);
		$data = self::tpl_compiler(array('nickname'=>$user['nickname'],'url'=>$link), 50007);
		if (!$data) {
			\classlib\logger::inst()->write("mail send tpl=50007 not found.");
			return false;
		}
		self::send($data['title'], $data['tpl'], $email);
	}
	
	//发送注册验证邮件/重发邮件
	public static function registersend($view, $userid, $email, $auto) {
		$vcode= self::setvcode($email, 1, $userid);
		$skey = sprintf('%s;%s;%d', $vcode, $email, $auto);
		$skey = \classlib\crypt\xxtea::encrypt($skey);
		$link = C\router::base_url().C\router::get_url('register', 'emailcheck').'?s='.urlencode($skey);
		$user = C\model::load('main.pl.userinfo')->set_dev($userid)->get_one($userid);
		$data = self::tpl_compiler(array('nickname'=>$user['nickname'], 'url'=>$link), 50004);
		if (!$data) {
			\classlib\logger::inst()->write("mail send tpl=50007 not found.");
			return false;
		}
		self::send($data['title'], $data['tpl'], $email);
	}
	
	//发送邮件资料信息
	public static function send($title, $html, $email) {
		if (!$email) {
			return ;
		}
		$field  = array('title'=>$title, 'msg'=>$html, 'receiver'=>$email,
			'sysid'=>self::sysid(), 'stime'=>C\config::$nowtime);
		C\model::load('main.log.mailsends')->new_one($field);
	}
	
	//发送邮件通知
	public static function dosend($address, $title, $msg, &$smtp) {
		static $mailer = FALSE;
		if (!$mailer) {
			require COREDIR.'/classlib/plugins/_phpmailer/class.phpmailer.php';
			$mailer = TRUE;
		}
		$mail           = new \PHPMailer();
		$mail->IsSMTP();
		$mail->SMTPDebug= false;
		$mail->CharSet	= 'UTF-8';
		$mail->Host 	= $smtp['stmp'];
		$mail->Port		= $smtp['port'];
		$mail->SMTPAuth = $smtp['isauth'];
		$mail->Username = $smtp['user'];
		$mail->Password = $smtp['loginpw'];
		$mail->From 	= $smtp['from'];
		$mail->FromName = $smtp['fromname'];
		$mail->AddAddress($address);
		$mail->IsHTML(true);
		$mail->Subject  = "=?utf-8?B?".base64_encode($title)."?=";
		$mail->Body     = $msg;
		if(!$mail->Send()) {
			return FALSE;
		}
		return TRUE;
	}
	
	/**
	 * 获取一台服务器的唯一标志码
	 * @return number
	 */
	public static function sysid() {
		$hash = \classlib\cache::inst('file')->get('os/sysid');
		if (!is_numeric($hash)) {
			$hash = mt_rand(1000, 9999).substr(C\config::$nowtime, 4);
			\classlib\cache::inst('file')->set('os/sysid', $hash);
		}
		return $hash;
	}
	
	/**
	 * 实现Email注册之后的自动跳转
	 * @param string $email
	 */
	public static function jump($email) {
		list(, $ltd) = explode('@', $email);
		$ckey= 'mail-jump'.$ltd;
		$url = C\model::$cacher->get($ckey);
		if (!$url) {
			$url  = 'http://mail.'.$ltd;
			if (!self::status_code($url)) {
				$url  = 'http://'.$ltd;
				if (!self::status_code($url)) {
					$url  = '/';
				}
			}
			C\model::$cacher->set($ckey, $url);
		}
		return $url;
	}
	
	/**
	 * 获取请求的状态码资料信息
	 * @param string $url
	 * @param number $timesec
	 * @return bool
	 */
	public static function status_code($url, $timesec = 3) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, $timesec);
		curl_setopt($ch, CURLOPT_HEADER, false);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 3);
		$info  = curl_exec($ch);
		if (!curl_errno($ch)) {
			$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			if ($code == 200 || $code == 301 || $code == 302) {
				return true;
			}
		}
		return false;
	}
	
	/**
	 * 充值成功发送邮件提醒
	 * @param unknown $email
	 * @param unknown $args
	 */
	public static function paynotify($email, $args) {
		$data = self::tpl_compiler($args, 50016);
		if ($data && $email) {//获取发送的模板信息
			self::send($data['title'], $data['tpl'], $email);
		}
	}
}